package com.gx.util.core.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * Created by gx on 2017/3/7.
 */
@Configuration
public class Initialization implements ApplicationListener<ContextRefreshedEvent> {

    private static final Logger log = LoggerFactory.getLogger(Initialization.class);

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //root application context 没有parent，他就是老大.

        if (event.getApplicationContext().getParent() == null) {
            //需要执行的逻辑代码，当spring容器初始化完成后就会执行该方法。
            log.info("\nSpring 容器加载完成\n______________\n");
            //初始化版本方法映射
            try {
                initEdtition();
            } catch (Exception ex) {
                log.error("反射加载初始化失败", ex);
            }
        }
        //或者下面这种方式
//        if (event.getApplicationContext().getDisplayName().equals("Root WebApplicationContext")) {
//        }
    }

    private  void initEdtition() throws Exception {
        Map<String, Object> map = SpringContextHolder.getBeans(Action.class);
        for (Object o : map.values()) {
            Action action = o.getClass().getAnnotation(Action.class);
            String version =  action.Version();
            for (Method m : o.getClass().getDeclaredMethods()) {
                ActionMethod actionMethod = new ActionMethod(o, m);
                EdtitionMethod.putMethodMap(version, m.getName(), actionMethod);
            }
        }
        log.info("初始化   EdtitionMethod================成功");
    }
}


